<template>
  <div class="container">
    <el-card style="margin: 15px 15px">
      <h3>试题录入</h3>
      <hr />
      <el-form
        :model="formData"
        class="main"
        label-width="120px"
        ref="form"
        :rules="rules"
      >
        <el-form-item label="学科:" prop="subjectID">
          <el-select
            v-model="formData.subjectID"
            @change="changeSubject"
            @blur="subjectID('subjectID')"
          >
            <el-option
              v-for="item in subjectOpt"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录:" prop="catalogID">
          <el-select
            v-model="formData.catalogID"
            @blur="subjectID('catalogID')"
          >
            <el-option
              v-for="item in catalogOpt"
              :key="item.id"
              :label="item.directoryName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="企业:" prop="enterpriseID">
          <el-select
            v-model="formData.enterpriseID"
            @blur="subjectID('enterpriseID')"
          >
            <el-option
              v-for="item in enterpriseOpt"
              :key="item.id"
              :label="item.company"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="城市:" prop="city">
          <el-select
            v-model="formData.province"
            @change="getCitys"
            @blur="subjectID('city')"
          >
            <el-option
              v-for="item in provincesOpt"
              :key="item"
              :label="item"
              :value="item"
            ></el-option> </el-select
          >&nbsp;
          <el-select v-model="formData.city">
            <el-option
              v-for="item in citysOpt"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="方向:" prop="direction">
          <el-select
            v-model="formData.direction"
            @blur="subjectID('direction')"
          >
            <el-option
              v-for="item in direction"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="题型:" prop="questionType">
          <el-radio-group v-model="formData.questionType">
            <el-radio
              v-for="item in questionType"
              :key="item.value"
              :label="item.value + ''"
            >
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="难度:" prop="difficulty">
          <el-radio-group v-model="formData.difficulty">
            <el-radio
              v-for="item in difficulty"
              :key="item.value"
              :label="item.value + ''"
            >
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="题干:" prop="question">
          <quill-editor
            class="richedit"
            v-model="formData.question"
            :options="editorOption"
            @blur="subjectID('question')"
          >
          </quill-editor>
        </el-form-item>
        <el-form-item label="选项:" v-if="formData.questionType !== '3'" prop="options">
          <div
            class="item_option"
            v-for="(item, index) in formData.options"
            :key="index"
          >
            <el-radio
              v-if="formData.questionType === '1'"
              :label="true"
              style="margin-right: 10px"
              v-model="item.isRight"
              @change="changRadio(item)"
              >{{ item.code }}:</el-radio
            >
            <el-checkbox
              v-if="formData.questionType === '2'"
              :label="true"
              style="margin-right: 10px"
              v-model="item.isRight"
              >{{ item.code }}:</el-checkbox
            >
            <el-input style="width: 240px" v-model="item.title" @blur="subjectID('options')"></el-input>
            <el-upload
              class="upload"
              :show-file-list="false"
              action="https://jsonplaceholder.typicode.com/posts/"
              :on-success="(res, file) => {uploadSuccess(item, res, file)}">
              <img v-if="item.img" :src="item.img" />
              <span v-else>上传图片</span>
              <i class="el-icon-circle-close" @click.stop="delBox(index)"></i>
            </el-upload>
          </div>
          <el-button
            type="danger"
            size="mini"
            :disabled="formData.questionType !== '2'"
            @click="addOpption"
            >+增加选项与答案</el-button
          >
        </el-form-item>
        <el-form-item label="解析视频:" prop="videoURL">
          <el-input style="width: 400px" v-model="formData.videoURL"></el-input>
        </el-form-item>
        <el-form-item label="答案解析:" prop="answer">
          <quill-editor
            class="richedit"
            v-model="formData.answer"
            :options="editorOption"
            @blur="subjectID('answer')"
          >
          </quill-editor>
        </el-form-item>
        <el-form-item label="题目备注:">
          <el-input
            type="textarea"
            class="textarea"
            :rows="4"
            style="width: 400px"
            v-model="formData.remarks"
          ></el-input>
        </el-form-item>
        <el-form-item label="试题标签:" prop="tags">
          <el-select multiple v-model="formData.tags"  @blur="subjectID('tags')">
            <el-option
              v-for="item in tagsOpt"
              :key="item.id"
              :label="item.tagName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <template>
            <el-button type="primary" @click="handleSubmit">确认提交</el-button>
          </template>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { list } from '@/api/hmmm/directorys.js'
import { simple } from '@/api/hmmm/subjects.js'
import { list as reqGetEnterprise } from '@/api/hmmm/companys.js'
import { provinces, citys } from '@/api/hmmm/citys.js'
import { direction, questionType, difficulty } from '@/api/hmmm/constants.js'
import { list as getTags } from '@/api/hmmm/tags.js'
import { add } from '@/api/hmmm/questions.js'
export default {
  name: 'Questions-new',
  // number integer 非必须  试题编号 后台自动生成（忽略）
  // subjectID string 非必须  学科
  // catalogID string 非必须  目录
  // enterpriseID string 非必须  企业
  // province string 非必须  城市
  // city string 非必须  地区
  // direction string 非必须  方向
  // questionType string 非必须  题型
  // difficulty string 非必须  难度
  // question string 非必须  题干
  // options object [] 非必须  选项 item 类型: object
  // ├─ code string 非必须  代码
  // ├─ title string 非必须  标题
  // ├─ img string 非必须  图片URL
  // ├─ isRight boolean 非必须  是否正确答案
  // videoURL string 非必须  解析视频
  // answer string 非必须  答案解析
  // remarks string 非必须  题目备注
  // tags string 非必须  试题标签
  // isPerfect boolean 非必须  是否精选题 后台自动生成（忽略）
  data () {
    return {
      editorOption: {
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
            [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表
            ['blockquote', 'code-block'], // 引用  代码块
            // [{ header: 1 }, { header: 2 }], // 1、2 级标题
            // [{ script: 'sub' }, { script: 'super' }], // 上标/下标
            // [{ indent: '-1' }, { indent: '+1' }], // 缩进
            // [{'direction': 'rtl'}],                         // 文本方向
            // [{ size: ['small', false, 'large', 'huge'] }], // 字体大小
            // [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题
            // [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色
            // [{ font: [] }], // 字体种类
            // [{ align: [] }], // 对齐方式
            // ['clean'], // 清除文本格式
            ['link', 'image', 'video'] // 链接、图片、视频
          ] // 工具菜单栏配置
        },
        placeholder: '', // 提示
        readyOnly: false, // 是否只读
        theme: 'snow', // 主题 snow/bubble
        syntax: true // 语法检测
      },
      rules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        city: [{ required: true, message: '请选择地区', trigger: 'change' }],
        direction: [
          { required: true, message: '请选择方向', trigger: 'change' }
        ],
        questionType: [
          { required: true, message: '请选择题型', trigger: 'change' }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'change' }
        ],
        question: [{ required: true, message: '请输入题干', trigger: 'blur' }],
        answer: [{ required: true, message: '请输入解析', trigger: 'blur' }],
        options: [{ required: true, message: '选项不能为空', trigger: 'blur' }],
        tags: [{ required: true, message: '试题标签不能为空', trigger: 'blur' }]
      },
      subjectOpt: [], // 学科
      catalogOpt: [], // 目录
      enterpriseOpt: [], // 企业
      provincesOpt: [], // 城市
      citysOpt: [], // 地区
      direction, // 方向
      questionType, // 题型
      difficulty, // 难度
      tagsOpt: [], // 试题标签
      imgUrl: '',
      formData: {
        subjectID: '',
        catalogID: '',
        enterpriseID: '',
        province: '',
        city: '',
        direction: '',
        questionType: '1',
        difficulty: '1',
        question: '',
        options: [
          { isRight: false, code: 'A', title: '', img: '' },
          { isRight: false, code: 'B', title: '', img: '' },
          { isRight: false, code: 'C', title: '', img: '' },
          { isRight: false, code: 'D', title: '', img: '' }
        ],
        videoURL: '',
        answer: '',
        remarks: '',
        tags: ''
      }
    }
  },
  created () {
    // 获取学科
    this.getSubjectList()
    // 获取企业
    this.getEnterprise()
    // 获取城市
    this.getProvinces()
  },
  methods: {
    async getSubjectList () {
      const { data } = await simple({ pagesize: 10000 })
      // console.log(data)
      this.subjectOpt = data
    },
    async changeSubject () {
      const {
        data: { items }
      } = await list()
      // console.log(items)
      this.getTags()

      const catalogOpt = items.filter(
        (item) => item.subjectID === this.formData.subjectID
      )
      this.catalogOpt = catalogOpt
    },
    async getEnterprise () {
      const {
        data: { items }
      } = await reqGetEnterprise({ pagesize: 10000 })
      // console.log(items)
      this.enterpriseOpt = items
    },
    getProvinces () {
      const res = provinces()
      // console.log(res, 222)
      this.provincesOpt = res
    },
    getCitys () {
      // console.log(this.formData.province)
      this.citysOpt = citys(this.formData.province)
    },
    async getTags () {
      const {
        data: { items }
      } = await getTags({ subjectID: this.formData.subjectID })
      console.log(items, 2312312)
      this.tagsOpt = items
    },
    // 提交
    handleSubmit () {
      // console.log(this.formData.tags, 11231232)
      this.$refs.form.validate(async (flag) => {
        if (!flag) return this.$message.error('请输入正确信息')
        this.formData.tags = this.formData.tags.join(',')
        console.log(this.formData)
        await add(this.formData)
        this.$message.success('录入试题成功')
        this.$router.push('/questions/list')
      })
    },
    addOpption () {
      this.formData.options.push({
        isRight: false,
        code: String.fromCharCode(this.formData.options.length + 65),
        title: '',
        img: ''
      })
    },
    // 校验
    subjectID (str) {
      this.$refs.form.validateField(str)
    },
    delBox (index) {
      if (index > 3) {
        this.formData.options.splice(index, 1)
      } else {
        this.$message.error('默认选择框不允许删除')
      }
    },
    uploadSuccess (item, res, file) {
      console.log(item, res, file)
      item.img = URL.createObjectURL(file.raw)
    },
    changRadio (state) {
      console.log(state)
      this.formData.options.forEach(item => { item.isRight = false })
      state.isRight = true
    }
  }
}
</script>

<style scoped lang="scss">
.main {
  padding-top: 20px;
  .richedit {
    height: 200px;
    // margin-left: 45px;
    margin-bottom: 50px;
  }
  .item_option {
    position: relative;
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    .upload {
      display: inline-block;
      margin-left: 5px;
      width: 100px;
      height: 56px;
      border: 1px dashed #ccc;
      border-radius: 5px;
      text-align: center;
      line-height: 56px;
    }
    i {
      position: absolute;
      left: 382px;
      top: -5px;
      color: gray;
      cursor: pointer;
    }
    img {
      display: inline-block;
      width: 100px;
      height: 56px;
    }
  }
}
</style>
